import { toRefs, ref } from "vue"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
import Query from "../../../zondy/lib/Query.js"
export const useQueryMonitor = () => {
  let monitorService = { name: "traffic", layerId: 3 }
  var monitorSource = new ol.source.Vector({})
  var monitorLayer = new ol.layer.Vector({
    source: monitorSource,
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        /* 填充色 */
        fill: new ol.style.Fill({
          color: "#ffff8d",
        }),
        /* 描边 */
        stroke: new ol.style.Stroke({
          color: "#283593",
          width: 3,
        }),
      }),
    }),
  })

  function queryMonitor() {
    mapState.value.map.addLayer(monitorLayer)
    Query.queryByLayer({ service: monitorService, success: queryMonitorSuccess })
  }
  function queryMonitorSuccess(e) {
    var format = new Zondy.Format.PolygonJSON()
    /* 将mapgis要素json反序列化为ol.feature类型数组 */
    var features = format.read(e)
    /* 将查询到的要素添加到高亮图层中 */
    monitorSource.addFeatures(features)

    mapState.value.map.on("click", ifMonitorFeature)

    mapState.value.map.on("pointermove",monitorMouseMove)
  }
  const ifMonitorFeature = function (evt) {
    eventElements.value.forEach(item => {
      mapState.value.map.removeOverlay(item)
    })
    var feature = mapState.value.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
      return feature
    })
    if (feature) {
      createpopu()
      const msg = feature.values_.values_
      measureTooltipElement.innerHTML = `编号:${msg["编号"]} <br/>
      位置:${msg["位置"]}<br/>
      <video src="/api/images/out.mp4" width="200" autoplay controls loop muted></video>
      `
      measureTooltip.setPosition(evt.coordinate)
    }
  }
  const monitorMouseMove = function (e) {
    var pixel = mapState.value.map.getEventPixel(e.originalEvent)
    var hit = mapState.value.map.hasFeatureAtPixel(pixel)
    mapState.value.map.getTargetElement().style.cursor = hit ? "pointer" : ""
  }
  let measureTooltipElement = null
  let measureTooltip = null
  let eventElements = ref([])
  function createpopu() {
    measureTooltipElement = document.createElement("div")
    measureTooltipElement.className = " tooltip-monitor"
    measureTooltip = new ol.Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      positioning: "bottom-center",
    })
    mapState.value.map.addOverlay(measureTooltip)
    eventElements.value.push(measureTooltip)
  }

  function closeQueryMonitor() {
    monitorSource.clear()
    mapState.value.map.removeLayer(monitorLayer)
    eventElements.value.forEach(item => {
      mapState.value.map.removeOverlay(item)
    })
    mapState.value.map.un("click", ifMonitorFeature)
    mapState.value.map.un("pointermove",monitorMouseMove)
  }

  return { queryMonitor,closeQueryMonitor }
}
